package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.MessageContact;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;

public class SendMessageDialogFragment extends DialogFragment {
  protected static final String EXTRA_ID = "com.isunland.managesystem.ui.extra_id";
  protected static final String EXTRA_NAME = "com.isunland.managesystem.ui.extra_name";
  private BaseVolleyActivity mActivity;
  private AlertDialog mDialog;
  private CurrentUser mUser;
  private ArrayAdapter<MessageContact> mAdapter;
  private ListView mListView;

  @Override public void onCreate(Bundle savedInstanceState) {
    mUser = CurrentUser.newInstance(getActivity());
    mActivity = (BaseVolleyActivity) getActivity();
    volleyPostCustomerUnitList();
    super.onCreate(savedInstanceState);
  }

  @Override public Dialog onCreateDialog(Bundle savedInstanceState) {

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    View v = getActivity().getLayoutInflater().inflate(R.layout.dialog_progress, null);
    builderSingle.setView(v);
    mDialog = builderSingle.create();

    return mDialog;
  }

  private void volleyPostCustomerUnitList() {

    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_MEMBER);
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("type", "user");
    params.put("orgCode", mUser.getMemberCode());
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        resolveResponseCustomerUnit(arg0);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  private void resolveResponseCustomerUnit(String arg0) {

    try {

      Type listType = new TypeToken<ArrayList<MessageContact>>() {
      }.getType();

      ArrayList<MessageContact> messageDialogs = new Gson().fromJson(arg0, listType);
      if (messageDialogs == null || messageDialogs.size() == 0) {

        return;
      }

      setAdapter(messageDialogs);
    } catch (Exception e) {

    }
  }

  private void setAdapter(ArrayList<MessageContact> messageDialogs) {
    mDialog.dismiss();

    if (mAdapter == null) {
      mAdapter = new ArrayAdapter<MessageContact>(getActivity(),
          android.R.layout.select_dialog_singlechoice, messageDialogs) {

        @Override public View getView(int position, View convertView, ViewGroup parent) {
          MessageContact user = getItem(position);
          if (convertView == null) {
            convertView = LayoutInflater.from(getContext())
                .inflate(android.R.layout.select_dialog_multichoice, parent, false);
          }
          TextView tvName = (TextView) convertView.findViewById(android.R.id.text1);

          tvName.setText(user.getName());

          return convertView;
        }
      };
    } else {
      mAdapter.clear();
      mAdapter.addAll(messageDialogs);
    }

    Builder builderSingle = new AlertDialog.Builder(getActivity());
    builderSingle.setAdapter(mAdapter, null);

    builderSingle.setPositiveButton(android.R.string.ok, new OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {

        StringBuilder idBuilder = new StringBuilder();
        StringBuilder nameBuilder = new StringBuilder();
        for (int i = mAdapter.getCount() - 1; i >= 0; i--) {
          if (mListView.isItemChecked(i)) {

            if (idBuilder.length() > 0) {
              idBuilder.append(",").append(mAdapter.getItem(i).getId());
            } else {
              idBuilder.append(mAdapter.getItem(i).getId());
            }
            if (nameBuilder.length() > 0) {
              nameBuilder.append(",").append(mAdapter.getItem(i).getName());
            } else {
              nameBuilder.append(mAdapter.getItem(i).getName());
            }
          }
        }

        if (getTargetFragment() == null) return;
        Intent i = new Intent();
        i.putExtra(EXTRA_ID, idBuilder.toString());
        i.putExtra(EXTRA_NAME, nameBuilder.toString());

        getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, i);
      }
    });
    AlertDialog alertDialog = builderSingle.create();

    mListView = alertDialog.getListView();
    mListView.setAdapter(mAdapter);
    mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

    mListView.setDivider(null);
    mListView.setDividerHeight(-1);

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {

      @Override public void onShow(DialogInterface dialog) {
        // setCheckedItems(((AlertDialog) dialog).getListView());
      }
    });

    alertDialog.show();
  }
}
